package com.weibei.web.resolver;

import com.alibaba.fastjson.JSONObject;
import com.weibei.common.annotation.LoginUser;
import com.weibei.common.constant.Constants;
import com.weibei.common.core.domain.RetCodeEnum;
import com.weibei.common.redis.util.RedisUtils;
import com.weibei.common.utils.response.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 */
@Configuration
@Slf4j
public class LoginUserHandlerResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisUtils redis;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Long.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory factory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        String token = request.getHeader("token");
        log.info("login token:" + token);
        if (token == null || token.isEmpty()) {
            return ResponseUtils.fail(RetCodeEnum.CODE_501.getCode(), RetCodeEnum.CODE_501.getDesc());
        }
        String userStr = null;
        try {
            userStr = redis.get(Constants.ACCESS_TOKEN + token);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseUtils.fail(RetCodeEnum.CODE_501.getCode(), RetCodeEnum.CODE_501.getDesc());
        }
        if (StringUtils.isBlank(userStr)) {
            return ResponseUtils.fail(RetCodeEnum.CODE_501.getCode(), RetCodeEnum.CODE_501.getDesc());
        }
        JSONObject userObj = JSONObject.parseObject(userStr);
        String userId = userObj.getString("userId");
        return Long.valueOf(userId);
    }
}
